/*
 * au.cpp
 *
 *  Created on: Feb 17, 2014
 *      Author: killerg
 */



#include "../bill_deps.h"
#include "platform_deps.h"

void send_res(http_server::p_request req, int errcode, const string &errmsg) {
	Json::Value ret_body;
	ret_body["errcode"] = errcode;
	ret_body["errmsg"] = errmsg;
	req->send_reply(200, to_cstr(ret_body));

    if (errcode != 0) {
        auto uri = evhttp_request_get_evhttp_uri(req->req);
        char buff[100];
        time_t now = time(NULL);
        strftime(buff,100,"%Y%m%d_%H%M%S",localtime(&now));
    	UTIL_LOG(E, "%s EPI_au errcode:%d, msg:%s, body:%s", buff, errcode, errmsg.c_str(), req->body.c_str());
    }
}

bool init_au() {
    g_https->handle("/bill/au", [](http_server::p_request req){
    	if (g_svrmgr->db_set >= 100) {
        	send_res(req, 4, "retry later");
        	return;
    	}

    	const Json::Value &req_body = to_json(req->body);
    	if (!req_body.isObject()) {
        	send_res(req, 1, "bad args");
            return;
    	}

    	int serverid = req_body.get("serverid", -1).asInt();
    	string account = req_body.get("account", "").asCString();
    	string orderId = req_body.get("orderId", "").asCString();
    	double payFee = req_body.get("payFee", 0.0f).asDouble();
    	string machinecode = req_body.get("mc", "").asCString();

    	if (serverid < 0 || account.empty() || orderId.empty() || payFee == 0.0f) {
        	send_res(req, 1, "bad args");
            return;
    	}

        auto playerinfo = g_svrmgr->get_player_info(serverid, account);
        if (NULL == playerinfo) {
        	send_res(req, 2, "no player info");
            return;
        }

        g_svrmgr->post_order(serverid, orderId, playerinfo->playerid, payFee, machinecode, [req](bool ok){
            if (ok)
            	send_res(req, 0, "success");
            else
            	send_res(req, 3, "other err");
        });
    });

    return true;
}
